<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">

            <div class="progressHint" v-if="hint">
              <NIcon size="20" class="iconStyle">
                <ErrorRound />
              </NIcon>
              <div style="white-space: pre-wrap" v-html="hint"></div>
            </div>
            <div class="progress">
              <div style="display:flex; margin-right: 10px;">
                <NIcon :size="20" class="iconStyle">
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span style="font-size: 18px;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="130"
                :model="formValue" style="width: 350px" label-align="right">

                <NSpace justify="space-between">
                  <NFormItem label="用车开始时间:" path="startTime">
                    <DatePicker input-readonly placeholder="请选择用车开始时间" type="datetime" class="commonWidth"
                      v-model:formatted-value="formValue.startTime" clearable :is-date-disabled="handleDateA"
                      :on-update:formatted-value="handleStartTime" />
                  </NFormItem>
                  <NFormItem label="用车结束时间:" path="endTime">
                    <DatePicker input-readonly placeholder="请选择用车结束时间" type="datetime" class="commonWidth"
                      v-model:formatted-value="formValue.endTime" clearable :is-date-disabled="handleDate"
                      :on-update:formatted-value="handleEndTime" />
                  </NFormItem>
                </NSpace>

                <NSpace justify="space-between">
                  <NFormItem label="用车人数:" path="useNumber">
                    <NInput placeholder="请输入用车人数" class="commonWidth" v-model:value="formValue.useNumber"
                      :allow-input="onlyIntNumber" />
                  </NFormItem>
                  <NFormItem label="用车人:" path="useMan">
                    <NInput placeholder="请输入用车人" class="commonWidth" v-model:value="formValue.useMan"
                      :allow-input="stopNull" />
                  </NFormItem>
                </NSpace>

                <NSpace justify="space-between">
                  <NFormItem label="联系人:" path="contacts">
                    <NInput placeholder="请输入联系人" class="commonWidth" v-model:value="formValue.contacts"
                      :allow-input="stopNull" />
                  </NFormItem>
                  <NFormItem label="联系电话:" path="phone">
                    <NInput placeholder="请输入联系电话" class="commonWidth" v-model:value="formValue.phone"
                      :allow-input="stopNull" />
                  </NFormItem>
                </NSpace>


                <NFormItem label="选择用车:" path="carIdList">
                  <NSelect multiple :options="vehicleList" v-model:value="formValue.carIdList" class="commonWidth"
                    :render-option="renderOption" @update-value="chosenCar" />
                </NFormItem>

                <NFormItem label="用车行程:" path="km">
                  <div style="display: flex; justify-content: space-between; width: 100%">
                    <div style="display: flex; flex-wrap: wrap">
                      <div v-for="(item, index) in formValue.useCarTripList" :key="index" style="
                          display: flex;
                          align-items: flex-start;
                          width: 350px;
                         height:40px
                        ">
                        <NFormItem :path="`useCarTripList[${index}].departureLocation`" :rule="{
                          required: false,
                          validator: (e: any, value: any) => renderMessage(value),
                          trigger: ['input', 'blur']
                        }">
                          <NInput placeholder="出发行程" class="commonWidthB" v-model:value="item.departureLocation"
                            :allow-input="stopNull" />
                        </NFormItem>
                        <div style="height: 34px; line-height: 34px; margin: 0 5px">至</div>
                        <NFormItem :path="`useCarTripList[${index}].destination`" :rule="{
                          required: false,
                          validator: (e: any, _: any) => renderMessageEnd(_),
                          trigger: ['input', 'blur']
                        }">
                          <NInput placeholder="到达行程" class="commonWidthB" v-model:value="item.destination"
                            :allow-input="stopNull" />
                        </NFormItem>
                        <NButton circle type="error" size="tiny" style="margin-left: 10px;margin-top:5px"
                          v-if="formValue.useCarTripList.length > 1" @click="DeteleTrip(item)">
                          <div style="height: 34px; line-height: 34px">—</div>
                        </NButton>
                      </div>
                    </div>
                  </div>
                </NFormItem>

                <NFormItem label=" ">
                  <NButton style="width: 115px" type="primary" @click="AddTrip" ghost>
                    添加行程
                  </NButton>
                </NFormItem>

                <NFormItem label="用车事由:" path="reasons">
                  <NInput placeholder="请输入用车事由" v-model:value="formValue.reasons" style="min-height: 100px"
                    type="textarea" :allow-input="stopNull" />
                </NFormItem>
                <NFormItem label="附件:" path="fileId">
                  <VUpload :file-list="fileList" @getList="handleUploadList" />
                </NFormItem>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25px; height: 25px" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(true)" v-if="workFlowList">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(false)" v-if="workFlowList">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示" :loading="loading">
      <div style="width: 300px; height: 100px; text-align: center; line-height: 100px">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, h, type VNode } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSelect,
  NSpin,
  useMessage,
  NModal,
  NIcon,
  NTooltip,
  type SelectOption,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import VUpload from '@/views/OA/Common/Upload.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute } from 'vue-router'
import { workFlow } from '@/enums/workFlow'
import VBackImg from '@/assets/images/back.png'
import { ApprovalFilled } from '@vicons/material'
import type { FormRules } from 'naive-ui'
import { subDays } from 'date-fns'
import { ErrorRound } from '@vicons/material'

const route = useRoute()
const tags = useTagStore().tags
const message = useMessage()

const props = defineProps({
  title: { type: String, default: () => '用车申请' },
  id: { type: [Number, String], default: () => null },
  flag: { type: [Number, String], default: () => null }
})

const spinShow = ref(false)
const renderMessage = (value: any) => {
  if (value?.length > 100) return new Error('字数不得超过100')
  return true
}
const renderMessageEnd = (value: any) => {
  if (value?.length > 100) return new Error('字数不得超过100')
  return true
}

const formValue = reactive<Record<string, any>>({
  draft: null, //草稿状态
  entityId: null, //流程实体id
  km: null,

  startTime: null,
  endTime: null,
  useNumber: null,
  useMan: null,
  contacts: null,
  phone: null,
  carIdList: null,
  useCarTripList: [
    {
      departureLocation: null,
      destination: null
    }
  ],
  reasons: null,
  fileId: null //文件id
})
const rules: FormRules = {
  carIdList: [
    {
      type: 'array',
      required: true,
      trigger: 'change',
      message: '请选择交通工具'
    }
  ],
  startTime: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择用车开始时间'
  },
  endTime: {
    required: true,
    message: '请选择用车结束时间',
    trigger: ['blur', 'change']
  },
  useNumber: {
    type: 'any',
    required: true,
    trigger: ['blur', 'change'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写用车人数')
      if (value < 1) return new Error('用车人数不得小于1')
      if (value.length > 2) return new Error('用车人数不得超过100')
      return true
    }
  },
  useMan: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写用车人')
      if (value.length > 100) return new Error('用车人字数不得超过100')
      return true
    }
  },
  contacts: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写联系人')
      if (value.length > 100) return new Error('联系人字数不得超过100')
      return true
    }
  },
  phone: {
    required: false,
    message: '请输入正确的联系电话',
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return true
      let regu = /^1[3-9][0-9]{9}$/
      return regu.test(value)
    }
  },
  km: {
    required: true,
    trigger: ['input', 'change'],
    message: '请填写行程'
  },
  reasons: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写用车事由')
      if (value.length > 100) return new Error('用车事由不得超过100')
      return true
    }
  }
}

// 禁用结束时间
const handleEndTime = (v: any, c: any) => {
  if (!v) return formValue.endTime = v
  c < new Date(formValue.startTime) ? message.error('结束时间不能早于开始时间') : formValue.endTime = v
}

// 禁用开始时间
const handleStartTime = (v: any, c: any) => {
  if (!v) return formValue.startTime = v
  if (formValue.endTime) {
    c > new Date(formValue.endTime) ? (message.error('结束时间不能早于开始时间'), formValue.startTime = null) : formValue.startTime = v
  } else {
    formValue.startTime = v
  }
}


// 日期禁用
const handleDate = (ts: any) => {
  return ts < new Date(subDays(new Date(formValue.startTime.split(' ')[0]), 1))
}

const handleDateA = (ts: any) => {
  if (formValue.endTime) {
    return ts > new Date(new Date(formValue.endTime))
  } else {
    return false
  }
}

//只能输入数字
const onlyIntNumber = (value: string) => {
  return !value || /^\d+$/.test(value)
}

//去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}

const renderOption = ({
  node,
  option
}: {
  node: VNode
  option: SelectOption
}) =>
  h(
    NTooltip,
    {
      placement: 'left'
    },
    {
      trigger: () => node,
      default: () => option.label
    }
  )

//行程
const DeteleTrip = (val: any) => {
  formValue.useCarTripList = formValue.useCarTripList.filter((item: any) => item != val)
}

const AddTrip = () => {
  formValue.useCarTripList.push({
    departureLocation: '',
    destination: ''
  })
}

//交通工具
const vehicleList: any = ref([])
const getVehicleType = async () => {
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'carList',
    override: {
      params: {
        page: 1,
        limit: 999999
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  vehicleList.value = []
  res.data.list.map((i: any) => {
    vehicleList.value.push({
      label: i.carName + '  ' + (i.licensePlate ? ' [' + i.licensePlate + ']' : '') + '  ' + (i.remarks ? '(' + i.remarks + ')' : ''),
      value: i.id,
      carStatus: i.carStatus
    })
  })
}
getVehicleType()


//用车选择
const workFlowStatus = ref(false)
const chosenCar = (_: any, info: any) => {
  workFlowStatus.value = false
  var i: any = ''
  for (i of info) {
    if (i.carStatus == '2') {
      workFlowStatus.value = true
    }
  }
  getWorkFlow()
}

// 获取流程id
const hint = ref()
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: workFlowStatus.value ? workFlow.YCSQLCSW : workFlow.YCSQLCSN
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.pxark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
  spinShow.value = false
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}

// 附件
const handleUploadList = (v: any) => (formValue.fileId = v)

// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const modalVisible = ref(false)
const contentContent = ref()

const confirm = (status: boolean) => {
  formValue.draft = status
  formRef.value?.validate(async (err) => {
    if (err) return
    const [errorCheck, resCheck] = await sendRequest({
      module: 'overTime',
      api: 'getWorkOvertimeApplyCheck',
      override: {
        data: {
          startTime: formValue.startTime,
          endTime: formValue.endTime,
          ids: [],
          type: 6
        }
      }
    })
    if (errorCheck) return message.error(errorCheck.message)
    if (resCheck.code !== 0) return message.error(resCheck.msg)
    if (resCheck.data as never !== '可以提交') return message.error(resCheck.data as never)
    contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
    modalVisible.value = true
  })
}

const againConfirm = async () => {
  loading.value = true
  if (props.id && !props.flag) {
    const [error, res] = await sendRequest({
      module: 'useCar',
      api: 'carUpdate',
      override: {
        data: {
          ...formValue,
          id: props?.id,
          userName: userName.value
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.msg)
    message.success(res.msg)
    goSubmit()
  } else {
    const [error, res] = await sendRequest({
      module: 'useCar',
      api: 'carSave',
      override: {
        data: formValue
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.msg)
    message.success(res.msg)
    goSubmit()
  }
  modalVisible.value = false
}

//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}


//获取修改详情
const fileList: any = ref([])
const userName = ref()
const getInfo = async () => {
  spinShow.value = true
  await getVehicleType()
  const [error, res] = await sendRequest({
    module: 'useCar',
    api: 'carItem',
    uri: {
      id: props?.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.fileList
  userName.value = res.data.userName
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    formValue[it] = res.data[it]
  })
  const tmp: any = []
  vehicleList.value.map((item: any) => {
    if (formValue.carIdList.includes(item.value)) {
      if (item.carStatus == '2') {
        tmp.push(item.label)
      }
    }
  })
  workFlowStatus.value = tmp?.length ? true : false
  spinShow.value = false
  await getWorkFlow()
}

watch(
  () => formValue.useCarTripList,
  () => {
    const flag1 = formValue.useCarTripList.every((it: any) => it.departureLocation)
    const flag2 = formValue.useCarTripList.every((it: any) => it.destination)
    flag1 && flag2 ? (formValue.km = '1') : (formValue.km = null)
  },
  { deep: true }
)


watch(
  () => props.id,
  () => {
    if (props.title == '编辑用车申请' && props.id) getInfo()
  },
  { deep: true, immediate: true }
)

onMounted(() => {
  getWorkFlow()
})
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240px;
}

.commonWidthB {
  width: 105px;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15px 20px;
    margin-bottom: 20px;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20px 0px;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20px 0 180px;
      background-color: #ebeceb;


      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40px;
          background-color: #fff;
          border-radius: 4px;
          padding: 5px 10px;
          margin-bottom: 10px;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5px;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 350px;
  max-width: 800px;
  min-height: 50px;
  background-color: #d5e2d8;
  border-radius: 5px;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350px;
  max-width: 800px;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
